package jp.co.systemi.asp.utils;

import java.io.Serializable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

public abstract class LazyLoadingList<E> extends AbstractList<E> implements
        Serializable {
    private static final Logger log = Logger.getLogger(LazyLoadingList.class
            .getName());
    private static final long serialVersionUID = 798209561952982661L;
    private int cacheStart = -1;
    private int cacheEnd = 0;
    private List<E> cache = null;

    public void setStart(int start){
        cacheStart = start;
    }
    @Override
    public E get(int index) {
        if (cache == null || index < cacheStart || cacheEnd < index) {
            cache = getPage(index, getCacheSize());
            cacheStart = index;
            cacheEnd = index + cache.size() - 1;
            log.info("RELOADED:" + cacheStart + "-" + cacheEnd);
        }
        return cache.get(index - cacheStart);
    }

    @Override
    public abstract int size();

    public abstract List<E> getPage(int start, int size);

    public abstract int getCacheSize();

    @Override
    public boolean remove(Object obj) {
        cacheEnd --;
        return cache.remove(obj);
    }

    @Override
    public void clear() {
        cacheStart = -1;
        cacheEnd = 0;
        cache = null;
    }

    @Override
    public boolean addAll(Collection<? extends E> arg0) {
        return cache.addAll(arg0);
    }
}
